﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AesonIntegrationTestLibrary.DataModel;
using AesonIntegrationTestLibrary.PubSubEvents;
using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.SqlServer.Dac;

namespace AesonIntegrationTestLibrary.Tools
{
    public static class DatabaseInitializer
    {
        public static async Task<AesonTest> InitializeDatabase(DatabaseinItializerModel dm, IEventAggregator eva)
        {
            AesonTest t = AesonTest.Create(eva);
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    t.AddEvent("Start Initializing ...");
                    t.AddEvent("Deleting database ...");
                    if (dm.ctx.Database.Exists())
                    {
                        if (dm.ctx.Database.Delete())
                        {
                            t.AddEvent("Database deleted successfully");
                        }
                        else
                        {
                            t.EndTest(TestStatut.Failed, "Database not deleted");
                        }
                    }
                    else
                    {
                        t.AddEvent("Database dont exist. Continuing");

                        t.AddEvent("Load BACPAC package...");
                        var pk = BacPackage.Load(dm.BacPacPath);
                        t.AddEvent("Create DacService...");
                        var svc = new DacServices(dm.TargetConnectionString);
                        t.AddEvent("Importing BacPac to Database...");
                      //  svc.ImportBacpac(pk, dm.TargetDatabaseName);
                        t.AddEvent("BacPac Deployed");
                        t.EndTest(TestStatut.Passed, "Test database deployed");
                    }

                }
                catch (Exception exc)
                {
                    t.EndTest(TestStatut.Failed,"ERROR : " + exc.Message + " "  + exc.StackTrace);
                }
            });
            return t;
        }
    }
}
